import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeWidget, QTreeWidgetItem, QTextEdit, QAction, QMenuBar, QVBoxLayout, QWidget, QSplitter
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QUrl
import markdown2
import os
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler
import threading
import webbrowser

'''
使用说明：
1. 安装依赖库：
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple PyQt5
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple PyQtWebEngine
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple markdown

2. 在根目录下运行：
python -m apps.reb.pyrsp_main
'''

class MarkdownViewer(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def start_web_server():
        server_address = ('127.0.0.1', 8088)
        # 指定网页文件所在的目录
        web_dir = os.path.dirname(__file__)
        os.chdir(web_dir)
        httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
        httpd.serve_forever()

    def initUI(self):
        # 创建菜单
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')

        exitAction = QAction(QIcon('exit.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)
        fileMenu.addAction(exitAction)

        # 设置主布局
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        layout = QVBoxLayout(self.centralWidget)

        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        layout.addWidget(splitter)

        # 创建树形控件
        self.treeWidget = QTreeWidget()
        splitter.addWidget(self.treeWidget)

        # 创建文本编辑器
        with open('./apps/reb/supports/tex-mml-chtml.js', 'r', encoding='utf-8') as fd:
            self.text_mml_chtml_js = fd.read()
        self.textEdit = QWebEngineView()
        htmlText = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <script>{self.text_mml_chtml_js}</script>
        </head>
        <body>
        雷达信号处理技术基于Python
        </body>
        </html>
        """
        self.textEdit.setHtml(htmlText)
        splitter.addWidget(self.textEdit)

        # 初始化树形控件
        self.initTree()

        self.setGeometry(300, 300, 600, 400)
        self.setWindowTitle('Markdown Viewer')

        
        # 创建线程
        thread = threading.Thread(target=MarkdownViewer.start_web_server)
        thread.daemon = True  # 直接设置 daemon 属性
        # 启动线程
        thread.start()

        # 等待线程结束
        # thread.join()

    def initEmf(self, root:QTreeWidget) -> None:
        '''
        初始化电磁学例程
        '''
        # 电磁学
        emf = QTreeWidgetItem(root)
        emf.setText(0, '电磁学')
        emf.setIcon(0, QIcon('folder.png'))
        # 平面波示例
        emf001 = QTreeWidgetItem(emf)
        emf001.setText(0, '平面波')
        emf001.setIcon(0, QIcon('file.png'))
        # 平面波反射
        emf002 = QTreeWidgetItem(emf)
        emf002.setText(0, '平面波反射和传播')
        emf002.setIcon(0, QIcon('file.png'))

    def initAntenna(self, root:QTreeWidget) -> None:
        '''
        初始化天线菜单
        '''
        parent = QTreeWidgetItem(root)
        parent.setText(0, '天线')
        parent.setIcon(0, QIcon('folder.png'))
        item001 = QTreeWidgetItem(parent)
        item001.setText(0, '有限长度偶极子')
        item001.setIcon(0, QIcon('file.png'))
        # 环形天线
        item002 = QTreeWidgetItem(parent)
        item002.setText(0, '平面阵列')
        item002.setIcon(0, QIcon('file.png'))
        # 线性阵列
        item003 = QTreeWidgetItem(parent)
        item003.setText(0, '线性阵列')
        item003.setIcon(0, QIcon('file.png'))

    def initRadarEquation(self, root:QTreeWidget) -> None:
        parent = QTreeWidgetItem(root)
        parent.setText(0, '雷达方程')
        parent.setIcon(0, QIcon('folder.png'))
        item001 = QTreeWidgetItem(parent)
        item001.setText(0, 'Hertzian Dipole')
        item001.setIcon(0, QIcon('file.png'))
        item002 = QTreeWidgetItem(parent)
        item002.setText(0, '基本雷达距离方程')
        item002.setIcon(0, QIcon('folder.png'))
        item002_001 = QTreeWidgetItem(item002)
        item002_001.setText(0, '功率密度')
        item002_001.setIcon(0, QIcon('file.png'))
        # 雷达接收功率
        item002_002 = QTreeWidgetItem(item002)
        item002_002.setText(0, '雷达接收信号')
        item002_002.setIcon(0, QIcon('file.png'))
        # 最小接收功率
        item002_003 = QTreeWidgetItem(item002)
        item002_003.setText(0, '最小接收功率')
        item002_003.setIcon(0, QIcon('file.png'))
        # 最大探测距离
        item002_004 = QTreeWidgetItem(item002)
        item002_004.setText(0, '最大探测距离')
        item002_004.setIcon(0, QIcon('file.png'))

    def initTree(self):
        # 设置树形控件的列数
        self.treeWidget.setColumnCount(1)

        # 创建树形控件的根节点
        root = QTreeWidgetItem(self.treeWidget)
        root.setText(0, "雷达信号处理Python版")
        root.setIcon(0, QIcon("folder.png"))
        # 2：电磁学
        self.initEmf(root)
        # 3：天线
        self.initAntenna(root)
        # 4：雷达方程
        self.initRadarEquation(root)
        # 5：雷达接收机
        # 6：目标识别
        # 7：脉冲压缩

        # # 添加一些子节点
        # for filename in os.listdir('.'):
        #     if filename.endswith('.md'):
        #         child = QTreeWidgetItem(root)
        #         child.setText(0, filename)
        #         child.setIcon(0, QIcon("file.png"))

        self.treeWidget.expandAll()
        self.treeWidget.clicked.connect(self.onTreeClicked)

    def onTreeClicked(self, index):
        raw_htmlText = None
        item = self.treeWidget.currentItem()
        if item.parent():
            # 如果点击的是文件，则在文本编辑器中显示Markdown内容
            item_title = item.text(0)
            if item_title == '平面波':
                from apps.reb.chp02.plane_waves_example import PlaneWaves
                self.subWindow = PlaneWaves()
                self.subWindow.show()
                webbrowser.open('http://127.0.0.1:8088/chp02/plane_waves_example.pdf')
            elif item_title == '平面波反射和传播':
                from apps.reb.chp02.reflection_transmission_example import ReflectionTransmission
                self.subWindow = ReflectionTransmission()
                self.subWindow.show()
                webbrowser.open('http://127.0.0.1:8088/chp02/reflection_transmission_example.pdf')
            elif item_title == '有限长度偶极子':
                from apps.reb.chp03.linear_wire_example import LinearWire
                self.subWindow = LinearWire()
                self.subWindow.show()
                webbrowser.open('http://127.0.0.1:8088/chp03/linear_wire_example.pdf')
            elif item_title == '平面阵列':
                from apps.reb.chp03.planar_array_example import PlanarArray
                self.subWindow = PlanarArray()
                self.subWindow.show()
                webbrowser.open('http://127.0.0.1:8088/chp03/planar_array_example.pdf')
            elif item_title == '线性阵列':
                from apps.reb.chp03.linear_array_example import LinearArray
                self.subWindow = LinearArray()
                self.subWindow.show()
                webbrowser.open('http://127.0.0.1:8088/chp03/linear_array_example.pdf')




class SubWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.setWindowTitle('Sub Window')
        self.setGeometry(100, 100, 300, 200)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mv = MarkdownViewer()
    mv.show()
    sys.exit(app.exec_())
